import type { PluginOption } from "vite";
import { join } from "node:path";
import { cwd } from "node:process";
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";

/** 该插件用于将loading样式注入到项目中 */
export const viteInjectAppLoadingPlugin = async (): Promise<PluginOption> => {
  const htmlTemplate = await getLoadingHtmlTemplate("app-loading.html");
  return {
    name: "vite-inject-app-loading",
    enforce: "pre",
    apply: "serve", //build标识只在打包阶段生效 serve 服务阶段生效，不配置全阶段都生效
    config(config, { command }) {
      //   console.log(config, "config 钩子");
    },
    configResolved(resolvedConfig) {
      //   console.log(resolvedConfig, "configResolved 钩子");
    },
    configureServer(server) {
      //   console.log(server, "configureServer 钩子");
    },
    // transformIndexHtml(html) {
    //   //   console.log(html, "transformIndexHtml 钩子");
    // },
    transformIndexHtml: {
      handler(html) {
        const reg = /<body\s*>/;
        html = html.replace(reg, `<body>${htmlTemplate}`);
        return html;
      },
      order: "pre",
    },
  };
};

/**
 *
 * @param templateUrl loading html 路径
 * 支持根目录下自定义loading.html全局加载
 */
const getLoadingHtmlTemplate = async (templateUrl: string) => {
  let loadingPath = join(cwd(), templateUrl);
  const isExist = existsSync(loadingPath);
  if (!isExist) {
    loadingPath = join(__dirname, "./app-loading.html");
  }
  return await readFile(loadingPath, "utf8");
};
